package com.qys.controller.upload;

import com.qys.common.utils.RSAUtil;
import com.qys.controller.entiry.FinalURL;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * Created by fangc on 2019-10-20 22:37
 */
@Controller
public class UploadController {
    private final Logger logger = Logger.getLogger(UploadController.class);
    @PostMapping(path = "/file/upload.do")
    @ResponseBody
    private JSONObject upload(@RequestParam("file") MultipartFile file,
                        HttpServletRequest request){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(FinalURL.UPLOAD_URL);
        CloseableHttpResponse response = null;
        JSONObject result = new JSONObject();
        try {
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setCharset(Charset.forName("utf-8"));
            multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题
            // 第一个文件
            String filesKey = "files";
            // 第二个文件(多个文件的话，使用可一个key就行，后端用数组或集合进行接收即可)
            multipartEntityBuilder.addBinaryBody(filesKey, file.getInputStream(), ContentType.MULTIPART_FORM_DATA,
                    URLEncoder.encode(file.getOriginalFilename(), "utf-8"));
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpPost.setEntity(httpEntity);
            JSONObject object = RSAUtil.getReqHeard();
            //设置请求头
            httpPost.setHeader("X-SID", object.optString("data"));
            httpPost.setHeader("X-Signature", object.optString("sign"));
            httpPost.setHeader("publicKey", object.optString("publicKey"));
            response = httpClient.execute(httpPost);// 执行提交
            HttpEntity responseEntity = response.getEntity();
            int status = response.getStatusLine().getStatusCode();
            result.put("status", status);
            if (status == 200) {
                if (responseEntity != null) {
                    // 主动设置编码，来防止响应乱码
                    String responseStr = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                    result.putAll(JSONObject.fromObject(responseStr));
                }
            } else if (status == 403) {
                result.put("msg", "非法请求");
            } else {
                result.put("msg", "服务器异常");
            }
        } catch (Exception e) {
            logger.error("上传文件：" + e.getMessage());
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            }catch (Exception e){
                logger.error("释放资源：" + e.getMessage());
            }
        }
        return result;
    }
}
